package com.caimiao.miao.service;

import android.content.Context;

import com.caimiao.miao.library.bluetooth.BluetoothControl;
import com.caimiao.miao.library.bluetooth.IBluetoothCode;
import com.caimiao.miao.library.bluetooth.state.IBtState;
import com.caimiao.miao.library.utils.CRC16Util;

import io.reactivex.Observable;

public class BleModel implements IBleContact.Model {
    private BluetoothControl mBtControl;
    private int mTicketOutNum;//出票总数数
    private int mTicketOutRemain;//剩余票数
    private byte[] mBuffer;

    @Override
    public void initBluetooth(Context context) {
        mBtControl = new BluetoothControl(context);
        closeBle();
        mBtControl.startAutoConnect("TYCP");
    }

    @Override
    public void closeBle() {
        mBtControl.close();
    }

    @Override
    public void setTicketOutNum(int num) {
        mTicketOutNum = num;
        mTicketOutRemain = num;
    }

    @Override
    public void setTicketOutRemain(int remain) {
        mTicketOutRemain = remain;
    }

    @Override
    public int getTicketOutRemain() {
        return mTicketOutRemain;
    }

    @Override
    public boolean needOut() {
        return mTicketOutRemain > 0;
    }

    @Override
    public byte[] getCommand(boolean isResend) {
        int size = IBluetoothCode.SET_TICKET_OUT.length;
        char[] command = new char[size + IBluetoothCode.SET_TICKET_OUT[size - 1]];
        for (int i = 0; i < size; i++) {
            command[i] = IBluetoothCode.SET_TICKET_OUT[i];
        }
        command[size] = (char) mTicketOutNum;//总票数
        command[size + 1] = (char) mTicketOutRemain;//剩余票数
        command[size + 2] = (char) 150;///150mm
        command[size + 3] = (char) (isResend ? 1 : 0);
        return CRC16Util.getSendBuf(command);
    }

    @Override
    public Observable<byte[]> getBtRead() {
        return mBtControl.read();
    }

    @Override
    public Observable<IBtState> getBtState() {
        return mBtControl.getBtState();
    }

    @Override
    public void write(byte[] value) {
        mBtControl.write(value);
    }

    @Override
    public void setReadBufferData(byte[] value) {
        if (value == null) return;
        int size = mBuffer == null ? 0 : mBuffer.length;
        byte[] temp = new byte[size + value.length];
        if (size > 0)
            System.arraycopy(mBuffer, 0, temp, 0, size);
        System.arraycopy(value, 0, temp, size, value.length);
        mBuffer = temp;
    }

    @Override
    public byte[] getReadBufferData() {
        return mBuffer;
    }

    @Override
    public void clearReadBufferData() {
        mBuffer = null;
    }

    @Override
    public void removeReadBufferByIndex(int index) {
        if (mBuffer != null && index >= 0 && index <= mBuffer.length) {
            byte[] temp = new byte[mBuffer.length - index];
            System.arraycopy(mBuffer, index, temp, 0, mBuffer.length - index);
            mBuffer = temp;
        }
    }

}
